layui.use(['layer','form','table','element'], function() {
    var layer = layui.layer, form = layui.form, table = layui.table,element = layui.element;
    var id = getUrlParam('id');
    show_loading();
    $.post(rurl('scm/materiel/classifyDetail'),{'id':id},function (res){
       if(isSuccessWarnClose(res)){
           var data = res.data,materiel = data.materiel,elements=data.elements;
           if(data.hsCodeNum>1){
               confirm_inquiry("所选物料存在不同归类税号，是否要合并归类？",function (){},function (){closeThisWin();});
           }
           if(!isEmpty(materiel.hsCode)){
               materiel['oldHsCode'] = materiel.hsCode;
           }
           form.val('form',materiel);
           if(materiel.brand.indexOf('|')!=-1){
               $('#brand').attr({'readonly':true}).addClass('layui-disabled').removeClass('required');
               // $('#brandZh').attr({'readonly':true}).addClass('layui-disabled').removeClass('required');
           }
           if(!elements||elements.length==0){
               obtainBrandType(materiel.brand);
           }
           obtainCiqNo(materiel.ciqNo);
           createElements(elements);
           obtainHsCodeDetail();
           analysisSmp();
       }
    });
    //绑定海关编码
    $('#hsCode').autocomplete({
        source: function (request, response) {
            $.post(rurl('system/customsCode/list'),{'id': trim(request.term)},function (res) {
                response($.map(res.data, function (item) {return {label: item.id+'('+item.name+')', value: item.id, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            var data = ui.item.data;
            if(data.id!=$('#oldHsCode').val()){
                form.val('form',{'hsCode':data.id,'oldHsCode':data.id,'csc':data.csc,'iaqr':data.iaqr,'tit':data.tit,'mfntr':data.mfntr,'gtr':data.gtr,'conrate':data.conrate,'vatr':data.vatr,'ter':data.ter,'exportRate':data.exportRate,'trr':data.trr});
                obtainElements();obtainCiqNo();
            }
        }
    }).focus(function (){
        $(this).select().autocomplete("search");
    });
    //绑定品牌
    $('#brand').autocomplete({
        source: function (request, response) {
            $.post(rurl('scm/materielBrand/select'),{'name': trim(request.term)},function (res) {
                response($.map(res.data, function (item) {return {label: '外文品牌：'+item.name+'，中文品牌： '+item.memo+' '+item.type+'：'+item.typeDesc, value: item.name, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            var data = ui.item.data;
            $('#brandType').find('option[value="'+data.type+'"]').attr({'selected':true});
            // $('#brandZh').val(data.memo);
            form.render('select');
            $(this).attr({'brand-type':data.type});
        }
    }).focus(function (){
        $(this).select().autocomplete("search");
    });
    //绑定品名要素
    $('#name').autocomplete({
        source: function (request, response) {
            $.post(rurl('scm/nameElements/list'),{'nameMemo': trim(request.term),'disabled':false},function (res) {
                response($.map(res.data, function (item) {return {label: item.nameMemo+' '+item.name+'：'+item.hsCode, value: item.name, data: item}}));
            });
        }, minLength: 0,autoFocus:true, delay: 300,
        select: function( event, ui ) {
            var data = ui.item.data;
            form.val('form',{'hsCode':data.hsCode,'oldHsCode':data.hsCode,'csc':data.csc,'iaqr':data.iaqr,'tit':data.tit,'mfntr':data.mfntr,'gtr':data.gtr,'conrate':data.conrate,'vatr':data.vatr,'ter':data.ter,'exportRate':data.exportRate,'trr':data.trr});
            obtainElements(data.elements);obtainCiqNo();
        }
    }).focus(function (){
        $(this).select().autocomplete("search");
    });
    $('.save-btn').click(function () {
        if(checkedForm($('.layui-form'))){
            var iaqr = $('#iaqr').val(),$isCapp=$('#isCapp'),$isCappNo=$('#isCappNo');
            if(!isEmpty(iaqr)){
                if(iaqr.indexOf("L")!=-1 && (isEmpty($isCapp.attr('checked')) && isEmpty($isCappNo.attr('checked')))){
                    layer.tips('民用商品入境验证（3C）<br/> (需要3C证书/需要3C目录鉴定) 请至少选择一个',$('#iaqr'),{tips: [3,'#0ba9f9'], time: 5000});
                    return;
                }
            }
            if(!isEmpty($isCapp.attr('checked')) && !isEmpty($isCappNo.attr('checked'))){
                layer.tips('(需要3C证书/需要3C目录鉴定) 不能同时选择',$('#sCapp'),{tips: [3,'#0ba9f9'], time: 5000});
                return;
            }
            formSub('scm/materiel/saveClassify',function (res) {
                parent.reloadList();
                closeThisWin('操作成功');
            });
        }
    });
    var isLoadLogs = false;
    element.on('tab(materialTab)', function(){
        var layId = this.getAttribute('lay-id');
        if(layId=="4"&&isLoadLogs==false){
            isLoadLogs = true;
            table.render({
                elem: '#table-log-list',method:'post',height: 'full-100',page: true,limits: limits,limit:limit,
                id:'table-log-list',response:{msgName:'message',statusCode: '1'},text:{none:'无归类记录'},
                url:rurl('scm/materielLog/list'),where:{'materielId':$('#id').val().split(',')[0]}
                , cols: [[
                    {type: 'numbers', title: '序号', width: 45}
                    ,{field: 'dateUpdated', title: '修改时间', width: 136}
                    ,{field: 'updateBy', title: '修改人', width: 80}
                    ,{field: 'changeContent', title: '修改内容'}
                ]]
            });
        }
    });
});
//获取申报要素
function obtainElements(elements){
    show_loading();
    $.get(rurl('system/customsElements/getByHsCode'),{'hsCode':$('#hsCode').val()},function (res) {
       if(isSuccess(res)){
           var data = res.data;
           if(!isEmpty(elements)){
              var velements = elements.split('|');
              if(velements.length==data.length){
                  $.each(data,function (i,o) {
                      o['val'] = trim(velements[i]);
                  });
              }
           }
           createElements(data);
       }
    });
}
//创建申报要素
function createElements(data) {
    var elements = [];
    $.each((data || []),function (i,o) {
        var eValue = isEmpty(o.val)?"":o.val,readonly = "";
        if ("品牌（中文或外文名称）" == o.name) {
            // eValue = '中文品牌：'+$('#brandZh').val().split('|')[0]+'，外文品牌：'+$('#brand').val().split('|')[0];
            eValue = trim($('#brand').val().split('|')[0]).replace('品牌','').replace('牌','').concat('牌');
            readonly = "readonly";
        } else if ("型号" == o.name) {
            eValue = returnModel() + "型";
            readonly = "readonly";
        }
        elements.push('<tr><td style="text-align: center">' + (i + 1) + '</td><td>&nbsp;&nbsp;' + o.name + '</td><td>');
        if(o.name=='品牌类型'){
            elements.push(brandType(eValue));
        }else if(o.name=='出口享惠情况'){
            elements.push(expBenefit(eValue));
        }else {
            elements.push('<input name="elementsVal" class="layui-input ' + (isEmpty(readonly) ? "" : "layui-disabled") + '" value="' + eValue + '" ' + readonly + '/>');
        }
        elements.push('</td></tr>');
    });
    $('#elements').html(elements.join(''));
    layui.form.render('select');
}
//获取CIQ编码
function obtainCiqNo(defVal) {
    var $ciqNo = $('#ciqNo');
    $ciqNo.get(0).length = 0;
    var hsCode = $('#hsCode').val();
    if(isEmpty(hsCode)){
        layui.form.render('select');
        return;
    }
    $.post(rurl('system/ciqCodes/list'),{'hsCode':hsCode},function (res) {
        if(isSuccess(res)){
            var data = res.data;
            if(data&&data.length>1){
                $ciqNo.append('<option value="">请选择</option>');
            }
            $.each((data || []),function (i,o) {
                $ciqNo.append('<option value="'+o.code+'">'+o.code+(isEmpty(o.typeName)?'':'('+o.typeName+')')+'</option>');
            });
            layui.form.render('select');
            if(!isEmpty(defVal)){
                layui.form.val('form',{ciqNo:defVal});
            }
        }
    });
}
//获取海关编码详情
function obtainHsCodeDetail() {
    var hsCode = $('#hsCode').val();
    if(isEmpty(hsCode)){return;}
    $.get(rurl('system/customsCode/detail'),{'id':hsCode},function (res) {
        if(isSuccess(res)){
            var data = res.data;
            layui.form.val('form',{'hsCode':data.id,'oldHsCode':data.id,'csc':data.csc,'iaqr':data.iaqr,'tit':data.tit,'mfntr':data.mfntr,'gtr':data.gtr,'conrate':data.conrate,'vatr':data.vatr,'ter':data.ter,'exportRate':data.exportRate,'trr':data.trr});
        }
    });
}
function brandType(defVal) {
    defVal = defVal || $('#brand').attr('brand-type');
    return ['<select name="elementsVal" id="brandType" lay-search="">','<option value="">品牌类型</option>','<option value="0" ',((defVal=='0')?'selected':''),'>0：无品牌</option>','<option value="1" ',((defVal=='1')?'selected':''),'>1：境内自主品牌</option>','<option value="2" ',((defVal=='2')?'selected':''),'>2：境内收购品牌</option>','<option value="3" ',((defVal=='3')?'selected':''),'>3：境外品牌(贴牌生产)</option>','<option value="4" ',((defVal=='4')?'selected':''),'>4：境外品牌(其他)</option>','</select>'].join('');
}
function expBenefit(defVal) {
    return ['<select name="elementsVal" id="expBenefit" lay-search="">','<option value="">出口享惠情况</option>','<option value="0" ',((defVal=='0')?'selected':''),'>0：出口货物在最终目的国(地区)不享受优惠关税</option>','<option value="1" ',((defVal=='1')?'selected':''),'>1：出口货物在最终目的国(地区)享受优惠关税</option>','<option value="2" ',((defVal=='2')?'selected':''),'>2：出口货物不能确定在最终目的国(地区)享受优惠关税</option>','<option value="3" ',((defVal=='3')?'selected':''),'>3：不适用于进口报关单</option>','</select>'].join('');
}
//香港管制物品查询
function querySmp() {
    openwin(rurl('basedata/hkControl/query.html?model='+id),'香港管制物品',{area: ['800px', '420px'],shadeClose:true});
}
//分析管制物品
function analysisSmp() {
    $.post(rurl('system/hkControl/list'),{'page':'1','limit':'1','model':returnModel(),'isControl':true},function (res) {
        if(isSuccess(res)){
            if(res.count>0){
                var $querySmp = $('#querySmp');
                $querySmp.after('<span class="layui-badge ml10">'+res.count+'</span>');
                layer.tips('此型号可能是香港管制类产品哦！！！', $querySmp,{tips: [3,'#0ba9f9'], time: 5000});
            }
        }
    });
}
//获取品牌类型
function obtainBrandType(name) {
    $.post(rurl('scm/materielBrand/findByName'),{'name':name},function (res) {
        if(isSuccess(res)){
            var data = res.data;
            if(data){
                $('#brand').attr({'brand-type':data.type});
            }
        }
    });
}
function returnModel() {
    var model = $('#model').val().split('|')[0];
    if (model.indexOf("##") > 0) {
        model = model.split("##")[0]
    }
    return model;
}